#include<unistd.h>
#include<iostream>
#include<sys/types.h>
#include<sys/wait.h>
using namespace std;   
void fatherread(int rfd)
{
    char buffer[1024];
    while(1)
    {
        int n=read(rfd,buffer,sizeof(buffer));
        if(n<0)//读失败
        {
            perror("read");
            exit(1);
        }
        else if(n==0)//读到了EOF
        {
            break;
        }
        else//读到了内容
        {
            cout<<buffer;
        }
    }
}
void childwrite(int wfd)
{
    char buffer[1024];
    int cnt=0;
    while(1)
    {
        int n=snprintf(buffer,sizeof(buffer),"this is child:%d\n",cnt++);
        if(n<0)
        {
            perror("snprintf");
            exit(1);
        }
        else if(n==0)//读到了EOF
        {
            break;
        }
        else//开始将buffer中的内容写入wfd
        {
            int m=write(wfd,buffer,n);
            if(m<0)
            {
                perror("write");
                exit(1);
            }
        }
        sleep(5);
    }
}
int main()
{
    int fd[2]={0};//fd[0]:读端，fd[1]:写端
    int n=pipe(fd);
    if(n<0)
    {
        perror("pipe");
        exit(1);
    }
    cout<<"Parent process: Pipe created successfully"<<endl;
    cout<<fd[0]<<" "<<fd[1]<<endl;
    pid_t child_pid=fork();
    //我们需要的场景是父读子写，所以父亲只需要关闭写端，子进程只需要关闭读端
    if(child_pid<0)
    {
        perror("fork");
        exit(1);
    }
    else if(child_pid==0)
    {
        //关闭读端
        close(fd[0]);
        //code
        childwrite(fd[1]);
        close(fd[1]);
    }
    else
    {
        //关闭写端
        close(fd[1]);
        //code
        fatherread(fd[0]);
        close(fd[0]);
    }
    waitpid(child_pid,NULL,0);
    return 0;
}